package com.four.bmm.controller;

import com.four.bmm.entity.Admin;
import com.four.bmm.service.AdminService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/AdminLoginServlet")
public class AdminLoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        System.out.println("|-------------------");
        String adminname = request.getParameter("adminname");
        String adminpwd = request.getParameter("adminpwd");
        String online = request.getParameter("online");
        System.out.println("online:"+online);
        Admin admin = new Admin(adminname, adminpwd);
        AdminService adminService = new AdminService();
        Admin loginAdmin = adminService.adminLogin(admin);
        if (loginAdmin != null) {
            session.setAttribute("loginAdmin", loginAdmin);
            if (online != null) {
                Cookie cookie = new Cookie(URLEncoder.encode(adminname, "UTF-8"), URLEncoder.encode(adminpwd, "UTF-8"));
                cookie.setMaxAge(60 * 60 * 3);//设置某个键值对的有效期，24小时
                response.addCookie(cookie);
            } else {
                Cookie cookie = new Cookie(URLEncoder.encode(adminname, "UTF-8"), URLEncoder.encode(adminpwd, "UTF-8"));
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
            System.out.println(loginAdmin.getAdminname());
            Cookie cookie = new Cookie(adminname, adminpwd);
            cookie.setMaxAge(60 * 60 * 3);
            response.addCookie(cookie);
            response.sendRedirect("back/index.jsp");
           // request.getRequestDispatcher("back/index.jsp").forward(request, response);
        }else {
            response.sendRedirect("login.jsp");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
